<?php

namespace App\Services;
use App\Http\Requests\Request;
use App\Mail\PassWord;
use App\Models\Customer;
use Illuminate\Support\Facades\Mail;

/**
 * Class HelpService
 * @package App\Services
 *
 * 公用方法集合类
 * 注意: 定义时直接定义public static function
 * <code>
 *   public function some_public_method($a)
 * </code>
 * 此类已在 config/app.php 中aliases数组中注册
 * 代码中的调用方法:
 * <code>
 *   ...
 *   Helper::some_public_method($a);
 * </code>
 */
class HelpService
{

    /**
     * 随机生成数字+字母组合的字符串
     * @param $len
     * @return array|string
     */
    public static function createRandomStr($len)
    {
        $str = array_merge(range(0, 9), range('a', 'z'), range('A', 'Z'));
        shuffle($str);
        $str = implode('', array_slice($str, 0, $len));
        return $str;
    }

    /**
     * <h2>Helper::get_filter</h2>
     * @return array 返回过滤信息数组, 如无过滤信息则返回空数组
     * <code>
     *   $filter = Helper::get_filter();
     * </code>
     *
     */
    public static function get_filter($filter = null)
    {
        // 前端传递的参数会把末尾的==给删除, 转码前必须加上。
        $raw = is_null($filter) ? request('f', '') . '==' : $filter;
        if (!empty($raw)) {
            if (strpos($raw, ' ') !== false) {
                $raw = str_replace(' ', '+', $raw);
            }
            $json_str = urldecode(base64_decode($raw));
            return json_decode($json_str, true);
        }
        return [];
    }

    /**
     * 编码转换
     * @param $string
     * @param bool $out_put
     * @return mixed|string
     */
    public static function transcoding($string, $out_put = true, $type = null){
        $system = $type ? $type : substr(PHP_OS,0,3);
        if ($system === 'WIN') {
            if ($out_put) {
                return mb_convert_encoding ($string, 'GBK', 'UTF-8');
            } else {
                return mb_convert_encoding ($string, 'UTF-8', 'GBK');
            }
        }
        return $string;
    }

    /**
     * 递归删除文件夹
     * @param $path
     * @return bool
     */
    public static function deleteDir($path){

        if(!is_dir($path)){
            return false;
        }

        $fh = opendir($path);
        while(($row = readdir($fh)) !== false){
            //过滤掉虚拟目录
            if($row == '.' || $row == '..'){
                continue;
            }

            if(!is_dir($path.'/'.$row)){
                unlink($path.'/'.$row);
            }
            self::deleteDir($path.'/'.$row);

        }
        closedir($fh);
        if(!rmdir($path)){
            return false;
        }
        return true;
    }

    public static function getFileContent($items, $dir, $default = [])
    {
        $result = [];
        if (is_array($items)) {
            foreach ($items as $item) {
                $file_name = storage_path($dir . $item . '.json');
                $result[$item] =
                    file_exists($file_name)?json_decode(file_get_contents($file_name)):$default;
            }
        } else {
            $file_name = storage_path($dir . $items . '.json');
            //如果传入参数所对应的json文件不存在，返回空字符串
            $result =
                file_exists($file_name)?json_decode(file_get_contents($file_name)):$default;
        }
        return $result;
    }

    public static function initEventSource() {
        array_map(function($headerStr){
            header($headerStr);
        }, [
            'content-type: text/event-stream',
            'cache-control: no-cache',
            'connection: keep-alive',
        ]);
        if (config('debug')) {
            header('Access-Control-Allow-Origin: http://localhost:8989');
            header('Access-Control-Allow-Credentials: true');
        }
    }

    public static function isMobile() {
        $userAgent = request()->header('user-agent');
        return str_contains($userAgent, ['Android', 'iPhone']);
    }

    public static function letterOperate($letter, $operate, $num) {
        $result = ord($letter);
        if ($operate === '+') {
           $result = $result + $num;
        } else if ($operate === '-') {
            $result = $result - $num;
        }
        $result = chr($result);
        return $result;
    }
    
    /**
     * 判断是否存在业务结构, 不存在就创建
     * @FunName: recursiveCreate
     * @Param: * @param int $i
     * @param $pid
     * @param $arr
     * @param $com_key
     * @return: 返回最后一次创建或者查询到的group_id
     */
    public static function recursiveCreate($i = 1, $pid, $arr, $com_key) {
        static $ids = [];
        if ($i < count($arr)) {
            $name = $arr[$i];
            $group_num = Group::where(['name'=>$name, 'parent_id'=>$pid, 'com_key'=>$com_key])->get()->count();
            if ($group_num == 0 && $i< count($arr)) {
                $i++;
                $group = new Group();
                $group->name = $name;
                $group->children = [];
                $group->parent_id = $pid;
                $pGroup = Group::find($pid);
                if (!is_null($pGroup)) {
                    $group->com_key = $pGroup->com_key;
                    $group->save();
                    array_push($ids, $group->id);
                    //把创建好的id添加到传过来的group_id模型的children中
                    $pChild = $pGroup->children;
                    array_push($pChild, $group->id);
                    $pGroup->children = $pChild;
                    $pGroup->save();
                }
                self::recursiveCreate($i, $group->id, $arr, $com_key);
            } else {
                $i++;
                $group_ids = Group::where(['name'=>$name, 'parent_id'=>$pid, 'com_key'=>$com_key])->get()->pluck('id')->all();
                array_push($ids, $group_ids[0]);
                self::recursiveCreate($i, $group_ids[0], $arr, $com_key);
            }
        }
        return $ids[count($ids)-1];
    }

    /**
     * 先判断文件是否存在  存在的话 文件名继续+1, 保存文件
     * @FunName: saveFile
     * @Param: * @param $path
     * @param int $j
     * @param $prefix
     */
    public static function saveFile($path, $j = 1, $prefix) {
        $fileName = $prefix.date('Y-m-d') . '_' . $j . '.csv';
        while ($j) {
            if (file_exists($path.$fileName)) {
                ++$j;
                $fileName = $prefix.date('Y-m-d') . '_' . $j . '.csv';
            } else {
                break;
            }
        }
        return $fileName;
    }
    
    // 随机生成一个不重复的数字给微信uin用
    public static function getRandUin() {
        $rand = mt_rand(time(), microtime(1)*10000);
        return 't_'.$rand;
    }

    /**
     * 判断是否是app请求
     * @return mixed
     */
    public static function fromApp() {
        return app('request')->is('api/v*');
    }

    /**
     * 如果$request->all()数据为空的话,说明是ios的请求,做特殊处理
     * @FunName: getRequest
     * @Param: * @param $data
     */
    public static function getRequest($data) {
        if (empty($data) || count($data) === 0) {
            $iosData = file_get_contents("php://input");
            $iosData = urldecode($iosData);
            if (substr($iosData, 0, 1) === "{") {
                return json_decode($iosData, true);
            } elseif (substr($iosData, 0, 1) === "=") {
                return json_decode(substr($iosData, 1), true);
            }
        } else {
            return $data;
        }
    }

    /**
     * 验证是否有权限
     * @param $_user
     * @param $action
     * @return bool
     */
    public static function isActions($_user, $action){
        $action_keys = $_user->role->actions;
        if (is_array($action_keys)) {
            if ($action_keys === []) {
                return true;
            } else {
                return in_array($action, $action_keys);
            }
        } else {
            return false;
        }
    }

    /**
     * 发送邮件
     * @param $res
     * @param $email
     * @param $password
     * @return mixed
     */
    public static function senEmail($res, $email, $password){
        if (isset($res)) {
            if (!empty($email)) {
                $obj = $res;
                $obj->password = $password;
                $obj->email = $email;
                Mail::to($obj->email)->send(new PassWord($obj));
            }
            return $res;
        }
        return $res;
    }

    // 根据客户id组合客户的房屋信息  id => address
    public static function groupHouse($id) {
        $customer = Customer::find($id);
        $attr = $customer->getAttributes();
        if (array_key_exists('houseInfo', $attr)) {
            $houseInfo = $customer->houseInfo;
            $arr = [];
            foreach ($houseInfo as $v) {
                $_id = (String)$v['_id'];
                $address = $v['address'];
                $arr = array_merge($arr, array($_id => $address));
            }
            return $arr;
        }
        return [];
    }

    public static function emptyListReturn() {
        return [
            'total' => 0,
            'data' => [],
        ];
    }
}
